﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using ContactSMS.Client.Models;
using ContactSMS.Client.Service;
using ContactSMS.Client.Views;
using ContactSMS.CoreBusiness;
using System.Collections.ObjectModel;

namespace ContactSMS.Client.ViewModels
{
    public partial class AddContactViewModel : ObservableObject
    {
        private readonly ContactService contactService;

        public ObservableCollection<Tags> Tags { get; set; }

        [ObservableProperty]
        private ObservableCollection<Tags> tag;

        [ObservableProperty]
        private AddContactModel addContactModel;
        [ObservableProperty]
        private AddPhoneModel addPhoneModel;

        public AddContactViewModel(ContactService contactService)
        {
            this.Tags = new ObservableCollection<Tags>();
            this.LoadTagsAsync();
            this.contactService = contactService;
            addContactModel = new AddContactModel();
            addPhoneModel = new AddPhoneModel();
        }

        public void LoadTagsAsync()
        {
            this.Tags.Add(new Tags { Id = 1, Name = "手机" });
            this.Tags.Add(new Tags { Id = 2, Name = "住宅" });
            this.Tags.Add(new Tags { Id = 3, Name = "单位" });
        }

        [RelayCommand]
        public async Task AddContact()
        {
            try
            {
                var result = await contactService.AddContactsAsync(AddContactModel);
                if (result != null && result.Success && result.Data != null)
                {
                    await Shell.Current.GoToAsync(nameof(ContactPage));
                }
                else
                {
                    await Application.Current.MainPage.DisplayAlert("Error", result?.Message ?? "Failed to load contacts", "OK");
                }
            }
            catch (Exception ex)
            {
                await Application.Current.MainPage.DisplayAlert("Error", ex.Message, "OK");
            }
        }
    }
}
